import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getTaskDetail, createTask, updateTask } from '@/api/task'
import { getDatasourceList, getDatabaseTables, getTableFields } from '@/api/datasource'

export default function useTaskForm() {
  const route = useRoute()
  const router = useRouter()
  const formRef = ref(null)
  const submitLoading = ref(false)
  const activeStep = ref(0)
  const datasourceList = ref([])
  const sourceTables = ref([])
  const sourceFields = ref([])
  const sourceTablesLoading = ref(false)
  const sourceFieldsLoading = ref(false)
  const fieldMapping = reactive({})

  // 是否为编辑模式
  const isEdit = computed(() => {
    return route.params.id !== undefined
  })

  // 获取数据源列表
  const fetchDatasourceList = async () => {
    try {
      const res = await getDatasourceList({ page: 1, size: 100 })
      datasourceList.value = res.data
    } catch (error) {
      console.error('获取数据源列表失败:', error)
    }
  }

  // 获取源表列表
  const fetchSourceTables = async (datasourceId) => {
    if (!datasourceId) return
    
    sourceTablesLoading.value = true
    try {
      const res = await getDatabaseTables(datasourceId)
      sourceTables.value = res.data
    } catch (error) {
      console.error('获取源表列表失败:', error)
    } finally {
      sourceTablesLoading.value = false
    }
  }

  // 获取源表字段列表
  const fetchSourceFields = async (datasourceId, tableName) => {
    if (!datasourceId || !tableName) return
    
    sourceFieldsLoading.value = true
    try {
      const res = await getTableFields(datasourceId, tableName)
      sourceFields.value = res.data.map(field => ({
        ...field,
        selected: true,
        required: field.is_primary
      }))
      
      // 初始化字段映射
      sourceFields.value.forEach(field => {
        if (field.selected) {
          fieldMapping[field.name] = field.name
        }
      })
    } catch (error) {
      console.error('获取源表字段列表失败:', error)
    } finally {
      sourceFieldsLoading.value = false
    }
  }

  // 处理源数据源变更
  const handleSourceChange = (value) => {
    form.source_table = ''
    form.incremental_field = ''
    sourceFields.value = []
    fetchSourceTables(value)
  }

  // 处理源表变更
  const handleSourceTableChange = (value) => {
    form.incremental_field = ''
    fetchSourceFields(form.source_id, value)
  }

  // 处理目标数据源变更
  const handleTargetChange = (value) => {
    // 如果目标表为空，则默认使用源表名
    if (!form.target_table && form.source_table) {
      form.target_table = form.source_table
    }
  }

  // 获取任务详情
  const getTask = async (id) => {
    try {
      const res = await getTaskDetail(id)
      Object.assign(form, res.data)
      
      // 解析字段映射
      if (form.field_mapping) {
        try {
          const mapping = JSON.parse(form.field_mapping)
          Object.assign(fieldMapping, mapping)
        } catch (e) {
          console.error('解析字段映射失败:', e)
        }
      }
      
      // 获取源表和字段
      await fetchSourceTables(form.source_id)
      await fetchSourceFields(form.source_id, form.source_table)
      
      // 根据字段映射更新字段选择状态
      sourceFields.value.forEach(field => {
        field.selected = fieldMapping[field.name] !== undefined
      })
    } catch (error) {
      console.error('获取任务详情失败:', error)
      ElMessage.error('获取任务详情失败')
    }
  }

  // 上一步
  const prevStep = () => {
    if (activeStep.value > 0) {
      activeStep.value--
    }
  }

  // 下一步
  const nextStep = async () => {
    if (activeStep.value < 3) {
      // 根据当前步骤验证表单
      let validateFields = []
      switch (activeStep.value) {
        case 0:
          validateFields = ['name', 'sync_type', 'sync_frequency', 'thread_count']
          if (form.sync_frequency === 'custom') {
            validateFields.push('cron_expression')
          }
          break
        case 1:
          validateFields = ['source_id', 'source_table', 'target_id', 'target_table']
          if (form.sync_type === 'incremental') {
            validateFields.push('incremental_field')
          }
          break
        case 2:
          // 检查是否至少选择了一个字段
          if (sourceFields.value.filter(f => f.selected).length === 0) {
            ElMessage.warning('请至少选择一个字段')
            return
          }
          break
      }
      
      if (validateFields.length > 0) {
        try {
          await formRef.value.validateFields(validateFields)
          activeStep.value++
        } catch (error) {
          console.log('表单验证失败:', error)
        }
      } else {
        activeStep.value++
      }
    }
  }

  // 提交表单
  const submitForm = async () => {
    // 更新字段映射
    const mapping = {}
    sourceFields.value.forEach(field => {
      if (field.selected) {
        mapping[field.name] = fieldMapping[field.name] || field.name
      }
    })
    form.field_mapping = JSON.stringify(mapping)
    
    submitLoading.value = true
    try {
      if (isEdit.value) {
        await updateTask(route.params.id, form)
        ElMessage.success('更新成功')
      } else {
        await createTask(form)
        ElMessage.success('创建成功')
      }
      router.push('/task/list')
    } catch (error) {
      console.error('提交表单失败:', error)
    } finally {
      submitLoading.value = false
    }
  }

  // 监听字段选择状态变化
  watch(sourceFields, (newFields) => {
    newFields.forEach(field => {
      if (field.selected && !fieldMapping[field.name]) {
        fieldMapping[field.name] = field.name
      }
    })
  }, { deep: true })

  onMounted(async () => {
    await fetchDatasourceList()
    
    if (isEdit.value) {
      await getTask(route.params.id)
    }
  })

  return {
    formRef,
    form,
    rules,
    isEdit,
    activeStep,
    submitLoading,
    datasourceList,
    sourceTables,
    sourceFields,
    sourceTablesLoading,
    sourceFieldsLoading,
    fieldMapping,
    prevStep,
    nextStep,
    submitForm,
    handleSourceChange,
    handleSourceTableChange,
    handleTargetChange
  }
}